package com.example.simple_android.annotation.impl;

import com.example.simple_android.annotation.InitView;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InitViewImpl {

    /**
     * 调用此方法，将初始化指定类中被InitView注解标记的Field
     *
     * @param o      指定的类的对象
     * @param method 用于初始化Field对象的方法，它接收一个int值，返回一个View对象
     */
    public static void initView(Object o, Method method) {
        Field[] declaredFields = o.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            InitView initView = field.getDeclaredAnnotation(InitView.class);
            if (initView == null) {
                continue;
            }
            int i = initView.viewId();
            method.setAccessible(true);
            field.setAccessible(true);
            try {
                field.set(o, method.invoke(o, i));
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
}
